//
//  HomePageViewController.m
//  JiuLe
//
//  Created by xcq on 15/11/1.
//  Copyright © 2015年 Fine. All rights reserved.
//
#import "Common.h"
#import <GeTuiSdk.h>
#import "RESideMenu.h"
#import "UserAlerts.h"
#import "JlUserManager.h"
#import "SocketManager.h"
#import "HomePageHeadView.h"
#import "HomeTableViewCell.h"
#import "LoginViewController.h"
#import "UIColor+RGBConverHex.h"
#import "HomePageViewController.h"
#import "ActivateViewController.h"
#import "MessageViewController.h"
#import "JLContentViewController.h"
#import "JLServiceWebViewController.h"

#define kDefaultHealth @"正常"

@interface HomePageViewController () <UIAlertViewDelegate>
@property (strong, nonatomic) NSString *currenDate;
@property (strong, nonatomic) HomePageHeadView *headView;

@end
 
@implementation HomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    addObserver(@selector(netRequest), @"refreshHome");
//    addObserver(@selector(refreshConnectStatus:), UserDeviceConnect);
//    addObserver(@selector(refreshActivity:), GetDataFromWatch);
//    [self queryActivity];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self showNavBarLeftImgAndRightTitle:nil
                            andRightImge:nil
                          andRightAction:NULL
                           andLeftAction:@selector(leftBtnAction)
                             andLeftImge:[UIImage imageNamed:@"more_ico"]];
    
    
    if ([SocketManager sharedInstance].socket.isConnected) {
        _headView.connectionStatusStr.text = @"已连接";
    }
    [self setUpTableView];
}

- (void)checkVersionUpdate {
    [Common checkVersionUpdate:^(BOOL isSuccess, BOOL isUpdate, BOOL isNewfeatures , NSDictionary *updateInfo) {
        if (isSuccess && isUpdate) {
            [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"有新版本可下载，是否前往更新" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil] show];
        }
    }];
}

- (void)queryActivity{
    [InterfaceNetManager RequestDeviceInfo:^(BOOL isSucceed, NSString *message, id data, NSError *error) {
        if (isSucceed) {
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary:(NSDictionary *)data];
            if (dic == nil || [[dic customObjectForkey:@"hasWatch"] integerValue] == 0) {
                [self goActivityViewController];
            }
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_model == nil) {
        [self netRequest];
    }
}


- (void)setUpTableView {
    _tableView.tableFooterView = [UIView new];
  
    CGSize tableHeadSize = CGSizeZero;
    if(iPhone5 || iPhone4s) {
        _headView = (HomePageHeadView *)[[[NSBundle mainBundle] loadNibNamed:@"HomePageHeadView"
                                                                            owner:self
                                                                     options:nil]
                                         objectAtIndex:1];
    } else if (iPhone6){
            _headView = (HomePageHeadView *)[[[NSBundle mainBundle] loadNibNamed:@"HomePageHeadView"
                                                                       owner:self
                                                                     options:nil]
                                         firstObject];
    } else {
        tableHeadSize = CGSizeMake(414, 200);
        _headView = (HomePageHeadView *)[[[NSBundle mainBundle] loadNibNamed:@"HomePageHeadView"
                                                                       owner:self
                                                                     options:nil]
                                         lastObject];
        _headView.frame = CGRectMake(0, 0, tableHeadSize.width , tableHeadSize.height);
//        [_headView updateConstraints];
    }
    _tableView.tableHeaderView = _headView;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self netRequest];
}

- (void)netRequest {
    [InterfaceNetManager RequestHomePageDataCompletion:^(BOOL isSucceed,
                                                         NSString *message,
                                                         id data,
                                                         NSError *error) {
        if (isSucceed) {
            JLLog(@"home page data : %@",data );
            _model = [HomeInfoModel objectWithKeyValues:data];
            if (_model.messageModels == nil) {
                _model.messageModels = [NSMutableArray new];
            }
            BOOL bol = NO;
            if ([[data objectForKey:@"recent_warn"] count] > 0) {
                for (NSDictionary *dic in [data objectForKey:@"recent_warn"]) {
                    MessageModel *message = [MessageModel objectWithKeyValues:dic];
                    [_model.messageModels addObject:message];
                    if (message.read != nil && [message.read boolValue] == 0 && message.type.intValue <= 3) {
                        bol = YES;
                    }
                }
            }
            if (bol) {
                [Common createRedPointToTabBar:1];
            } else {
                [Common removeRedPoint:1];
            }
            [self setUpHeadView];
            [self.tableView reloadData];
        } else {
            if ([message isKindOfClass:[NSString class]]) {
                TIPS(message);
            } else {
                TIPS(@"首页请求失败！");
            }
        }
    }];
}

- (void)refreshConnectStatus:(NSNotification *)notification {
    if ([notification.object boolValue]) {
        _headView.connectionStatusStr.text = @"已连接";
        _headView.connectionStatus.image = [UIImage imageNamed:@"home_lj"];

    } else {
        _headView.connectionStatusStr.text = @"未连接";
        _headView.connectionStatus.image = [UIImage imageNamed:@"home_weilianjie"];
    }
}

- (void)refreshActivity:(NSNotification *)obj {
    NSArray *arr = obj.object;
    if (![arr isKindOfClass:[NSArray class]] && arr.count < 2) {
        return;
    }
    NSNumber *activity = [arr firstObject];
    _headView.ExerciseLabel.text = SecurityGet(([NSString stringWithFormat:@"%@步",activity]),kDefaultHealth);
    _headView.PILabel.text = SecurityGet(([NSString stringWithFormat:@"%@",[arr objectAtIndex:2]]),@"----");
    _headView.HRLabel.text = SecurityGet(([NSString stringWithFormat:@"%@",[arr objectAtIndex:3]]),@"----");
}

- (void)setUpHeadView {
    if ([SocketManager sharedInstance].socket.isConnected) {
        [[SocketManager sharedInstance] writeActiveGet];
    }
    _headView.PILabel.text = SecurityGet(_model.bloodOxygen,@"----");
    _headView.HRLabel.text = SecurityGet(_model.heartRate, @"----");
    _headView.ExerciseLabel.text = SecurityGet(_model.activity, kDefaultHealth);
    _headView.sleepModel.text = SecurityGet(_model.sleep, @"----");
    if ([_model.uname isEqualToString:@""] || _model.uname == nil) {
        _headView.userName.text = @"亲，您好";
    } else {
        _headView.userName.text = [_model.uname stringByAppendingString:@"，您好"];
    }
    JlUserManager *manager = [JlUserManager shareInstance];
    _headView.connectionStatusStr.text = @"未连接";
    _headView.connectionStatus.image = [UIImage imageNamed:@"home_weilianjie"];
    [[NSUserDefaults standardUserDefaults] setObject:_model.uname forKey:JiuLeUserName];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:JiuLeIsConnection];
    [_headView.userIcon sd_setImageWithURL:[NSURL URLWithString:manager.userInfo.hdpurl] placeholderImage:[UIImage imageNamed:@"photo_default"]];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 3;
            break;
        case 2:
            return 1;
            break;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        if (iPhone6P) {
            return 100;
        } else if (iPhone6) {
            return 20;
        } else if (iPhone5) {
            return 10;
        }
    }
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"HomeTableViewCell" owner:self options:nil]lastObject];
    cell.indicator.hidden = NO;
    cell.rightarrow.hidden = NO;
//    NSInteger idex = ([model.type integerValue])-1;
    switch (indexPath.section) {
        case 0:{
            cell.statusImg.image = [UIImage imageNamed:@"ld_jj_ico"];
            cell.statusName.text = @"紧急呼叫";
            //TODO:有网络请求后赋值
            cell.indicator.hidden = YES;
            //设置CELL属性
            [self setCellStatusWithCell:cell
                                  Model:[[_model messageModels] firstObject]
                                   Type:1];
        }
            break;
        case 1:{
            if (indexPath.row == 0) {
                cell.statusImg.image = [UIImage imageNamed:@"ld_bj"];
                cell.statusName.text = @"健康报警";
                //TODO:有网络请求后赋值
                cell.indicator.hidden = YES;
             
                [self setCellStatusWithCell:cell
                                      Model:[[_model messageModels] objectAtIndex:1]
                                       Type:2];
            } else if (indexPath.row == 1) {
                cell.statusImg.image = [UIImage imageNamed:@"home_yj"];
                cell.statusName.text = @"健康预警";
                //TODO:有网络请求后赋值
                [self setCellStatusWithCell:cell
                                      Model:[[_model messageModels] objectAtIndex:2]
                                       Type:3];
            } else if (indexPath.row == 2) {
                cell.statusImg.image = [UIImage imageNamed:@"home_dd"];
                cell.statusName.text = @"跌倒报警";
                //TODO:有网络请求后赋值
                cell.indicator.hidden = YES;
//                [self setCellStatusWithCell:cell
//                                      Model:[[_model messageModels] objectAtIndex:3]
//                                       Type:4];
            }
        }
             break;
        case 2:{
            cell.statusImg.image = [UIImage imageNamed:@"guahao_ico"];
            cell.statusName.text = @"相关挂号";
            //TODO:有网络请求后赋值
            cell.indicator.hidden = YES;
//            [self setCellStatusWithCell:cell
//                                  Model:[[_model messageModels] objectAtIndex:4]
//                                   Type:5];
        }
             break;
    }
    
            return cell;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 52;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HomeTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (indexPath.section == 2) {
        JLServiceWebViewController *serviceWeb = [[JLServiceWebViewController alloc] initWithNibName:@"JLServiceWebViewController" bundle:nil];
        [self.navigationController pushViewController:serviceWeb animated:YES];
    } else {
        if (((MessageViewController *)[(BaseNavController *)[[JlUserManager shareInstance].baseTab.viewControllers objectAtIndex:1] topViewController]).dataSouce == nil) {
            [JlUserManager shareInstance].baseTab.selectedIndex = 1;
            [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:FirstJoinAppClickHomeCellGoMessage];
            [[NSUserDefaults standardUserDefaults] setObject:cell.date.text forKey:FirstJoinAppClickHomeCellGoMessageTime];
        } else {
            [JlUserManager shareInstance].baseTab.selectedIndex = 1;
//            postNotification();
            postNotificationWithObject(HomePagePostMessageReloadWithType,(cell.date.text));
        }
    }
}

- (void)leftBtnAction
{
    [self.sideMenuViewController presentLeftMenuViewController];
}

- (void)RightBtnAction {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定要退出吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 500;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        if (alertView.tag == 500) {
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:UserInfoUserDefault];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:UserDataPassWord];
            LoginViewController *login = getStoryOfControllerInstance(@"LoginViewController");
            self.view.window.rootViewController = login;
        } else {
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/ebus/id%@?mt=8&uo=4",kAPPID]]];
        }
    }
}

- (void)goActivityViewController {
    ActivateViewController *activate = [[ActivateViewController alloc] initWithNibName:@"ActivateViewController" bundle:nil];
    BaseNavController *active = [[BaseNavController alloc] initWithRootViewController:activate];
    self.view.window.rootViewController = active;
}

- (void)setCellStatusWithCell:(HomeTableViewCell *)cell Model:(MessageModel *)model Type:(NSInteger)type{
    cell.indicator.hidden = YES;
    cell.statusNum.text = @"";
    cell.date.text = @"";
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    if (model!=nil && model.mid != nil && model.time != nil) {
        if ([model.read boolValue] == 0) {      
            if ([model.type integerValue] == type) {
                cell.indicator.hidden = NO;
                cell.index = [model.type integerValue];
                if (model.time != nil) {
                    cell.date.text = [dateformatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:[model.time integerValue]]];
                }
                return;
            }
        }
    }
    cell.statusNum.text = @"";
}

@end
